import { Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository } from "typeorm";
import { JobLogEntity } from "@entity/monitor/jobLog.entity";
import { ListJobLogDTO } from "@dto/monitor/jobLog.dto";
import { resBuild } from "@utils/resBuild";
import { DownloadExcelService } from "@service/common/downloadExcel";

@Provide()
export class JobLogService {
  @Inject()
  ctx: Context;

  @InjectEntityModel(JobLogEntity)
  jobLogEntity: Repository<JobLogEntity>;

  @Inject()
  protected downloadExcelService: DownloadExcelService;

  // 列表
  async list(queryParams: ListJobLogDTO) {
    const queryBuilder = this.jobLogEntity.createQueryBuilder('entity');
    if(queryParams.jobName) {
      queryBuilder.andWhere(`entity.jobName like "%${queryParams.jobName}%"`)
    }
    if(queryParams.jobGroup) {
      queryBuilder.andWhere(`entity.jobGroup = :jobGroup`, { jobGroup: queryParams.jobGroup })
    }
    if(queryParams.status) {
      queryBuilder.andWhere(`entity.status = :status`, { status: queryParams.status })
    }
    if(queryParams["params[beginTime]"] && queryParams["params[endTime]"]) {
      queryBuilder.andWhere(`entity.createTime BETWEEN :beginTime AND :endTime`, {
        beginTime: queryParams["params[beginTime]"] + ' 00:00:00',
        endTime: queryParams["params[endTime]"] + ' 23:59:59',
      })
    }

    if(queryParams.pageNum && queryParams.pageSize) {
      queryBuilder.skip((queryParams.pageNum - 1) * queryParams.pageSize).take(queryParams.pageSize)
    }

    const [rows, total] = await queryBuilder.getManyAndCount()
    return resBuild.list(rows, total)
  }

  // 删除
  async delete(jobLogId: string) {
    const ids = jobLogId.split(',').map(id => Number(id));
    await this.jobLogEntity.delete(ids);
    return resBuild.success()
  }

  // 详情
  async detail(jobLogId: number) {
    const detailInfo = await this.jobLogEntity.findOneBy({
      jobLogId,
    });
    return resBuild.data(detailInfo)
  }

  // 导出
  async export(queryParams: ListJobLogDTO) {
    // 默认导出全部，去掉分页参数
    delete queryParams.pageNum;
    delete queryParams.pageSize;
    let headers = [
      { label: "日志编号", prop: "jobLogId", },
      { label: "任务名称", prop: "jobName", },
      { label: "任务组名", prop: "jobGroup", },
      { label: "调用目标字符串", prop: "invokeTarget", },
      { label: "日志信息", prop: "jobMessage", },
      { label: "执行状态", prop: "status", },
      { label: "执行时间", prop: "createTime", width: 25 },
    ];
    const { rows } = await this.list(queryParams)
    return this.downloadExcelService.downloadExcel({
      headers: headers,
      data: rows,
      sheetName: '定时任务日志',
    });
  }
}
